package com.woniu.controller;

import com.github.pagehelper.PageInfo;
import com.woniu.common.JsonResult;
import com.woniu.constant.SystemConstant;
import com.woniu.dto.TreeDTO;
import com.woniu.pojo.Auth;
import com.woniu.pojo.Role;
import com.woniu.service.AuthService;
import com.woniu.service.RoleService;
import com.woniu.util.TreeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.reflect.generics.tree.Tree;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private AuthService authService;

    @RequestMapping("/roleList")
    @ResponseBody
    public List roleList(){
        return roleService.findRoles();
    }
     @RequestMapping("/list")
     @ResponseBody
    public Map list(@RequestParam(value = "page" ,defaultValue = "1",required = false)Integer currentPage,
                    @RequestParam(value = "rows",defaultValue = "5",required = false)Integer pageSize,
                    @RequestParam(value = "roleName",required = false)String roleName){
           List<Role>list=roleService.findRolesByPage(currentPage,pageSize,roleName);
        PageInfo pageInfo=new PageInfo(list);
        Map map=new HashMap();
        map.put("total",pageInfo.getTotal());
        map.put("rows",pageInfo.getList());
        return map;
    }
    @RequestMapping("loadTree")
    @ResponseBody
    public List<TreeDTO> loardTree(Integer roleId){
        //根据角色id查询该角色所拥有的默认权限（authIds）
        String authIds=roleService.findAuthIdsByRoleId(roleId);
        //构建tree的节点数据，通过递归构造所有节点数据
        List<Auth>list=authService.findAll();
        List<TreeDTO>authList= TreeUtils.buildTree(authIds,list, SystemConstant.TREE_ROOT);
        return authList;
    }
    @RequestMapping("/updateAuth")
    @ResponseBody
    public JsonResult updateRoleAuth( String authIds,Integer roleId){
        try {
            roleService.updateRoleAuthIds(authIds,roleId);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.erro();
        }
        return JsonResult.ok();
    }
}